<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Excel;

use PDOManager;
use Lang2;
use Illuminate\Support\Facades\Log;

class ContactController extends Controller{

    public function listTasks(Request $request){


        //check login
        $currentUser = null;
        $sid = $request->header('sid');
        $auth = $this->handleAuth($request);
        if($auth){
           $result_arr = array(
               'code'=>$auth["code"],
               'msg'=>$auth["message"]
           );
           return response()->json($result_arr);
        }else{
            $currentUser = $this->getCurrentUser();
        }

		// $user_id = $request->input('user_id');
		// $bywho = $request->has('bywho') ? $request->input('bywho') : 'user';
		// $pageNow = $request->input('pageNow');
		// $pageSize = $request->input('pageSize');

		//full, location, none
//        $user = DB::table('users')->where("sid", "=", $sid)->first();
		$type = $request->input('type');
		$keyword = $request->input('keyword'); //全文，或者lnt,lat



		
		if($type === "full"){
		    //  http://localhost:7888/tt201801/public/index.php/user/listContact?type=full&keyword=c&sid=dfsfasdfasdf
			if(empty($keyword)){
				$result_arr = array(
						'code'=>1,
						'msg'=>'请输入关键词',
						'result' => array()
				);
				return response()->json($result_arr);
			}else{
//			    echo $currentUser->id . "---" . $keyword;
                $db = PDOManager::getDB();
                $sql = "select * from contact where user_id=$currentUser->id and 
                      (
                      real_name LIKE :keyword_real_name
                      or company LIKE :keyword_real_name
                      or department LIKE :keyword_real_name
                      or title LIKE :keyword_real_name
                      or addr LIKE :keyword_real_name
                      or extra LIKE :keyword_real_name
                      )";
                $likeParam = "%" . $keyword . "%";
                $rows = PDOManager::findAll($db, $sql, array(
//                    "user_id"=>$currentUser->id,
                    "keyword_real_name"=>$likeParam
                ));

                $result_arr = array(
                    'code'=>0,
                    'msg'=>'',
                    'result' => $rows
                );
                return response()->json($result_arr);
                $db = null;
            }

		}else if($type === "location"){
            if(empty($keyword)){
                $result_arr = array(
                    'code'=>2,
                    'msg'=>'请输入lnt,lat，注意下划线拼起来',
                    'result' => array()
                );
                return response()->json($result_arr);
            }else{
                // http://localhost:7888/tt201801/public/index.php/user/listContact?type=location&keyword=116.291298,40.120932&sid=dfsfasdfasdf

                $location = explode(',', $keyword);
                $resArr = array();

                $db = PDOManager::getDB();
                $sql = "select * from contact where user_id=:user_id";
                $tasks = PDOManager::findAll($db, $sql, array(
                    "user_id"=>$currentUser->id,

                ));
                if(Lang2::isEmpty($tasks)){
                    $result_arr = array(
                        'code'=>0,
                        'msg'=>'',
                        'result' => array()
                    );
                    return response()->json($result_arr);
                }

                foreach ($tasks as $task){
                    //116.330392 40.029946

                    try{
                        if($task["lnt"] && $task["lat"]){
                            $task['distance'] =(int) Lang2::getDistance($location[0], $location[1], $task["lnt"], $task["lat"]);

                            $limit = 20 * 1000; //20Km
                            if($task['distance'] <= $limit){
                                $resArr[] = $task;
                            }else{
                            }
                        }
                    }catch (\Exception $e){
                        Log::error("计算距离出错--" . $e->getMessage() . "--传入参数：" . $keyword);
                        $result_arr = array(
                            'code'=>9,
                            'msg'=>'传入的经纬度格式不对',
                            'result' => $resArr
                        );
                        return response()->json($result_arr);
                    }

                }

                $result_arr = array(
                    'code'=>0,
                    'msg'=>'',
                    'result' => $resArr
                );

                return response()->json($result_arr);
            }
            ///计算经纬度距离吧
        }else {
            //不用任何筛选
            $tasks = DB::table('contact')->where("user_id", "=", $currentUser->id)->orderBy('id','desc')->get();

        }

		$result_arr = array(
				'code'=>0,
				'msg'=>'ok',
				'result' => $tasks
				);

    	//return response(json_encode($result_arr));
		return response()->json($result_arr);
		
    }

    public function getContactDetail(Request $request){


        //check login
        $currentUser = null;
        $sid = $request->header('sid');
        $auth = $this->handleAuth($request);
        if($auth){
            $result_arr = array(
                'code'=>$auth["code"],
                'msg'=>$auth["message"]
            );
            return response()->json($result_arr);
        }else{
            $currentUser = $this->getCurrentUser();
        }

        $contact_id = $request->input('contact_id');

        $result_arr = array();

        if(empty($contact_id)){
            //新建
            $result_arr = array(
                'code'=>1,
                'msg'=>'必须指定contact_id'
            );
            return response()->json($result_arr);

        }else{
            //update--结束
            $contact = DB::table('contact')->where('id','=', $contact_id)->first();
            if($contact){
                $result_arr = array(
                    'code'=>0,
                    'msg'=>'ok',
                    'result'=>$contact
                );
            }else{
                $result_arr = array(
                    'code'=>404,
                    'msg'=>'找不到这个联系人',
                    'result'=>""
                );
            }

        }

        return response()->json($result_arr);

    }

	public function addTask(Request $request){

        //check login
        $currentUser = null;
        $sid = $request->header('sid');
        $auth = $this->handleAuth($request);
        if($auth){
            $result_arr = array(
                'code'=>$auth["code"],
                'msg'=>$auth["message"]
            );
            return response()->json($result_arr);
        }else{
            $currentUser = $this->getCurrentUser();
        }

        $contact_id = $request->input('contact_id');
		$user_id = $request->input('user_id');
		$real_name = $request->input('real_name');
		$phone = $request->input('phone');
		$email = $request->input('email');
		$birthday = $request->input('birthday');
		$gender = $request->input('gender');
		$shengxiao = $request->input('shengxiao');
		$marriage = $request->input('marriage');
		$company = $request->input('company');
		$department = $request->input('department');
		$title = $request->input('title');
		$lnt = $request->input('lnt');
		$lat = $request->input('lat');
		$addr = $request->input('addr');
		$extra = $request->input('extra');

		$result_arr = array();


		if(empty($user_id)){
			$result_arr = array(
					'code'=>1,
					'msg'=>'必须传入user_id'
			);
			return response()->json($result_arr);
		}
		if(empty($real_name)){
			$result_arr = array(
					'code'=>2,
					'msg'=>'必须传入客户姓名'
			);
			return response()->json($result_arr);
		}
		if(empty($phone)){
			$result_arr = array(
					'code'=> 3,
					'msg'=>'必须传入手机号'
			);
			return response()->json($result_arr);
		}
//		if(empty($birthday)){
//			$result_arr = array(
//					'code'=>1,
//					'msg'=>'必须传入生日'
//			);
//			return response()->json($result_arr);
//		}
//		if(empty($gender)){
//			$result_arr = array(
//					'code'=>'1',
//					'msg'=>'必须传入性别'
//			);
//			return response()->json($result_arr);
//		}
//		if(empty($shengxiao)){
//			$result_arr = array(
//					'code'=>1,
//					'msg'=>'必须传入生肖'
//			);
//			return response()->json($result_arr);
//		}
//		if(empty($marriage)){
//			$result_arr = array(
//					'code'=>1,
//					'msg'=>'必须传入婚姻状况'
//			);
//			return response()->json($result_arr);
//		}
		if(empty($company)){
			$result_arr = array(
					'code'=>4,
					'msg'=>'必须传入公司'
			);
			return response()->json($result_arr);
		}
//		if(empty($department)){
//			$result_arr = array(
//					'code'=>1,
//					'msg'=>'必须传入部门'
//			);
//			return response()->json($result_arr);
//		}
//		if(empty($title)){
//			$result_arr = array(
//					'code'=>1,
//					'msg'=>'必须传入职位'
//			);
//			return response()->json($result_arr);
//		}
//		if(empty($lnt)){
//			$result_arr = array(
//					'code'=>1,
//					'msg'=>'必须传入lnt'
//			);
//			return response()->json($result_arr);
//		}
//		if(empty($lat)){
//			$result_arr = array(
//					'code'=>1,
//					'msg'=>'必须传入纬度'
//			);
//			return response()->json($result_arr);
//		}
		if(empty($addr)){
			$result_arr = array(
					'code'=>5,
					'msg'=>'必须传入详细地址'
			);
			return response()->json($result_arr);
		}

		if(empty($lnt) || empty($lat)){
            try{
                $url='http://restapi.amap.com/v3/geocode/geo?key=f9625737c0a3b28c97b54db3a3549513&address=' . $addr;//f9625737c0a3b28c97b54db3a3549513
                if($result=file_get_contents($url))
                {
                    //{"status":"1","info":"OK","infocode":"10000","count":"1","geocodes":[{"formatted_address":"北京市昌平区回龙观西大街|21号","province":"北京市","citycode":"010","city":"北京市","district":"昌平区","township":[],"neighborhood":{"name":[],"type":[]},"building":{"name":[],"type":[]},"adcode":"110114","street":"回龙观西大街","number":"21号","location":"116.335846,40.079930","level":"门牌号"}]}
                    //"location":"116.335846,40.079930"
                    $json_array = json_decode($result, true);
                    $res= explode(',', $json_array['geocodes'][0]["location"]);
                    $lnt = $res[0];
                    $lat = $res[1];
                }

            }catch (\Exception $e){
                $lnt = "";
                $lat = "";
                Log::error("高德查询经纬度的接口错误-" . $e->getMessage(), [
                    "result"=>$result,
                    "addr"=>$addr,
                ]);
            }
        }

		if(empty($contact_id) || $contact_id == -1 || $contact_id == 0){
			//新建
			$contact_id = DB::table('contact')->insertGetId([
					'user_id'=>$user_id,
					'real_name'=>$real_name,
					'phone'=>$phone,
					'birthday'=>$birthday,
					'gender'=>$gender,
					'shengxiao'=>$shengxiao,
					'marriage'=>$marriage,
					'company'=>$company,
					'department'=>$department,
					'title'=>$title,
					'lnt'=>$lnt,
					'lat'=>$lat,
					'addr'=>$addr,
					'extra'=>$extra,
					'create_time'=>time() . "",
					'update_time'=>time() . ""
				]);
			$result_arr = array(
					'code'=>0,
					'msg'=>'ok',
					'result'=>array(
							'contact_id'=>$contact_id
					)
			);

		}else{
			//update--结束
			DB::table('contact')->where('id','=', $contact_id)->update([
				'real_name'=>$real_name,
				'phone'=>$phone,
				'birthday'=>$birthday,
				'gender'=>$gender,
				'shengxiao'=>$shengxiao,
				'marriage'=>$marriage,
				'company'=>$company,
				'department'=>$department,
				'title'=>$title,
				'lnt'=>$lnt,
				'lat'=>$lat,
				'addr'=>$addr,
				'extra'=>$extra,
				'update_time'=>time() . ""
			]);
			$result_arr = array(
					'code'=>0,
					'msg'=>'ok',
					'result'=>array(
							'contact_id'=>$contact_id
					)
			);
		}

		return response()->json($result_arr);
	}

	public function deleteTask(Request $request){

        //check login
        $currentUser = null;
        $sid = $request->header('sid');
        $auth = $this->handleAuth($request);
        if($auth){
            $result_arr = array(
                'code'=>$auth["code"],
                'msg'=>$auth["message"]
            );
            return response()->json($result_arr);
        }else{
            $currentUser = $this->getCurrentUser();
        }

        $contact_id = $request->input('contact_id');

		$result_arr = array();


		if(empty($contact_id)){
			//新建
			$result_arr = array(
					'code'=>1,
					'msg'=>'必须指定要删除的id'
			);
			return response()->json($result_arr);

		}else{
			//update--结束
			DB::table('contact')->where('id','=', $contact_id)->delete();
			$result_arr = array(
					'code'=>0,
					'msg'=>'ok',
					'result'=>""
			);
		}

		return response()->json($result_arr);
	}

}

?>